package top.guagua.web.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.alibaba.fastjson.JSON;
import top.guagua.core.util.BaseResponse;
import top.guagua.core.util.BussinessException;
import top.guagua.core.util.ErrorEnum;


public class WebHandlerException implements HandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(WebHandlerException.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object o, Exception e) {
        logger.error(e.getMessage(),e);
        ModelAndView mv = new ModelAndView("error");

        if(o == null || o instanceof ResourceHttpRequestHandler){
            return mv;
        }
        HandlerMethod handler = (HandlerMethod) o;
        ResponseBody ajax = handler.getMethod().getAnnotation(ResponseBody.class);
        if (ajax != null) {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                BaseResponse resp = new BaseResponse();
                if (e instanceof BussinessException) {
                    resp.setCode(((BussinessException) e).getCode());
                    resp.setMessage(e.getMessage());
                }else if(e instanceof RemoteConnectFailureException){
                    resp.setCode("500");
                    resp.setMessage("服务调用出错");
                }else if(e instanceof IllegalArgumentException){
                    resp.setCode("400");
                    resp.setMessage(e.getMessage());
                } else {
                    resp.setCode(ErrorEnum.SYSTEM_ERR.getCode());
                    resp.setMessage(ErrorEnum.SYSTEM_ERR.getValue());
                }
                writer.write(JSON.toJSONString(resp));
                writer.flush();
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return new ModelAndView();
        } else {
            if (e instanceof BussinessException) {
                mv.addObject("code",((BussinessException) e).getCode());
                mv.addObject("msg",e.getMessage());
            } else {
                mv.addObject("code", 500);
                mv.addObject("msg", "系统错误");
            }
            return mv;
        }


    }

}
